// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.lang.text;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class OrderedSublistRequest {

	public static OrderedSublistRequest valueOf(String sublistRequest) throws IllegalArgumentException {
		OrderedSublistRequest request;

		try {
			request = new OrderedSublistRequestParser(sublistRequest)
					.parseExpression()
					.getResult();
		}
		catch (ParseException e) {
			throw new IllegalArgumentException("Input "
					+ sublistRequest
					+ " cannot be parsed: "
					+ e.getMessage());
		}

		return request;
	}

	List<OrderByClause> orderByClauses;
	Set<Integer> includedPages;
	boolean includeAllPages;

	public List<OrderByClause> getOrderByClauses() {
		return Collections.unmodifiableList(orderByClauses);
	}

	public Set<Integer> getIncludedPages() {
		if (includeAllPages) {
			return Collections.emptySet();
		}
		return Collections.unmodifiableSet(includedPages);
	}

	public boolean isPageIncluded(int number) {
		if (includeAllPages) {
			return true;
		}
		return includedPages.contains(number);
	}

	public boolean isPageExcluded(int number) {
		if (includeAllPages) {
			return false;
		}
		return !includedPages.contains(number);
	}

	public <T> Collection<T> buildSublist(Collection<T> allItems) {
		if(includeAllPages || allItems == null) {
			return allItems;
		}
		
		List<T> selectedItems = new LinkedList<T>();
		int i = 0;
		for(T item : allItems) {
			i++;
			if(includedPages.contains(i)) {
				selectedItems.add(item);
			}
		}
		
		return selectedItems;
	}
}
